package com.ruoyi.qif.service.impl;

import java.util.List;
import java.util.Objects;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.html.EscapeUtil;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.qif.domain.RoomCategoryVO;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.qif.mapper.QifRoomMapper;
import com.ruoyi.qif.domain.QifRoom;
import com.ruoyi.qif.service.IQifRoomService;
import com.ruoyi.common.core.text.Convert;

import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import static com.ruoyi.common.utils.ShiroUtils.getLoginName;

/**
 * 锜风公寓-房间Service业务层处理
 *
 * @author David
 * @date 2025-10-05
 */
@Service
public class QifRoomServiceImpl implements IQifRoomService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private QifRoomMapper qifRoomMapper;
    @Autowired
    protected Validator validator;
    /**
     * 查询锜风公寓-房间
     *
     * @param roomId 锜风公寓-房间主键
     * @return 锜风公寓-房间
     */
    @Override
    public QifRoom selectQifRoomByRoomId(Long roomId) {
        return qifRoomMapper.selectQifRoomByRoomId(roomId);
    }


    /**
     * 查询锜风公寓-房间列表
     *
     * @param qifRoom 锜风公寓-房间
     * @return 锜风公寓-房间
     */
    @Override
    public List<QifRoom> selectQifRoomList(QifRoom qifRoom) {
        return qifRoomMapper.selectQifRoomList(qifRoom);
    }

    /**
     * 新增锜风公寓-房间
     *
     * @param qifRoom 锜风公寓-房间
     * @return 结果
     */
    @Override
    public int insertQifRoom(QifRoom qifRoom) {
        qifRoom.setCreateTime(DateUtils.getNowDate());
        qifRoom.setCreateBy(getLoginName());
        return qifRoomMapper.insertQifRoom(qifRoom);
    }

    /**
     * 修改锜风公寓-房间
     *
     * @param qifRoom 锜风公寓-房间
     * @return 结果
     */
    @Override
    public int updateQifRoom(QifRoom qifRoom) {
        qifRoom.setUpdateTime(DateUtils.getNowDate());
        qifRoom.setUpdateBy(getLoginName());
        return qifRoomMapper.updateQifRoom(qifRoom);
    }

    /**
     * 批量删除锜风公寓-房间
     *
     * @param roomIds 需要删除的锜风公寓-房间主键
     * @return 结果
     */
    @Override
    public int deleteQifRoomByRoomIds(String roomIds) {
        return qifRoomMapper.deleteQifRoomByRoomIds(Convert.toStrArray(roomIds));
    }

    /**
     * 删除锜风公寓-房间信息
     *
     * @param roomId 锜风公寓-房间主键
     * @return 结果
     */
    @Override
    public int deleteQifRoomByRoomId(Long roomId) {
        return qifRoomMapper.deleteQifRoomByRoomId(roomId);
    }

    /**
     * 导入房间数据
     *
     * @param roomList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<QifRoom> roomList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(roomList) || roomList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (QifRoom room : roomList) {
            if (!Objects.isNull(room)){
                try {
                    // 验证是否存在这个房间号
                    QifRoom r = qifRoomMapper.selectRoomNum(room.getRoomNum());
                    if (StringUtils.isNull(r)) {
                        BeanValidators.validateWithException(validator, room);
                        qifRoomMapper.insertQifRoom(room);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、房间号 " + room.getRoomNum() + " 导入成功");
                    } else if (isUpdateSupport) {
                        BeanValidators.validateWithException(validator, room);
                        room.setRoomId(r.getRoomId());
                        room.setRoomNum(r.getRoomNum());
                        room.setUpdateBy(operName);
                        qifRoomMapper.updateQifRoom(room);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、房间号 " + room.getRoomNum() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、房间号 " + room.getRoomNum() + " 已存在");
                    }
                } catch (Exception e) {
                    failureNum++;
                    String roomNum = room.getRoomNum();
                    if (ExceptionUtil.isCausedBy(e, ConstraintViolationException.class)) {
                        roomNum = EscapeUtil.clean(roomNum);
                    }
                    String msg = "<br/>" + failureNum + "、房间号 " + roomNum + " 导入失败：";
                    failureMsg.append(msg + e.getMessage());
                    log.error(msg, e);
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 按分类查询房间数据
     */
    @Override
    public RoomCategoryVO selectRoomByCategory(QifRoom qifRoom) {
        RoomCategoryVO categoryVO = new RoomCategoryVO();

        // 1. 单间（类型01，状态3=空房 或 5=预定）
        QifRoom singleParam = new QifRoom();
        singleParam.setRoomType("01");
        // 状态为3（空房）或5（预定）
        singleParam.setStatus("3,5"); // 注意：需在Mapper中支持IN查询
        copyQueryParam(qifRoom, singleParam);
        categoryVO.setSingleRoom(qifRoomMapper.selectQifRoomList(singleParam));

        // 2. 一房一厅（类型02，状态3或5）
        QifRoom oneBedParam = new QifRoom();
        oneBedParam.setRoomType("02");
        oneBedParam.setStatus("3,5");
        copyQueryParam(qifRoom, oneBedParam);
        categoryVO.setOneBedroom(qifRoomMapper.selectQifRoomList(oneBedParam));

        // 3. 两房一厅（类型03，状态3或5）
        QifRoom twoBedParam = new QifRoom();
        twoBedParam.setRoomType("03");
        twoBedParam.setStatus("3,5");
        copyQueryParam(qifRoom, twoBedParam);
        categoryVO.setTwoBedroom(qifRoomMapper.selectQifRoomList(twoBedParam));

        // 4. 维修中（状态2，不限制类型）
        QifRoom maintenanceParam = new QifRoom();
        maintenanceParam.setStatus("2");
        copyQueryParam(qifRoom, maintenanceParam);
        categoryVO.setMaintenance(qifRoomMapper.selectQifRoomList(maintenanceParam));

        return categoryVO;
    }

    // 修复copyQueryParam：移除强制设置status的逻辑
    private void copyQueryParam(QifRoom source, QifRoom target) {
        target.setUnit(source.getUnit());
        target.setRoomENum(source.getRoomENum());
        target.setRoomNum(source.getRoomNum());
        target.setRent(source.getRent());
        target.setDeposit(source.getDeposit());
        target.setCheckInTime(source.getCheckInTime());
        target.setExpirationTime(source.getExpirationTime());
    }
}
